package top.swimmer.boot.util;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by xiaoyou on 7/7/16.
 */
public final class ModelUtils {

    private ModelUtils() {

    }

    public static <T> T convert(Class<T> modelClass, Map<String, Object> map) throws Exception {
        BeanInfo beanInfo = Introspector.getBeanInfo(modelClass); // 获取类属性
        T t = modelClass.newInstance(); // 创建 JavaBean 对象

        // 给 JavaBean 对象的属性赋值
        PropertyDescriptor[] propertyDescriptors =  beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            Method setter = property.getWriteMethod();
            if (setter != null && map.containsKey(property.getName()) && map.get(property.getName()) != null) {
                setter.invoke(t, map.get(property.getName()));
            }
        }
        return t;
    }

    public static <T> Map<String, Object> degrade(final T entity) throws Exception {
        if (entity == null) {
            return null;
        }
        BeanInfo beanInfo = Introspector.getBeanInfo(entity.getClass()); // 获取类属性

        final PropertyDescriptor[] propertyDescriptors =  beanInfo.getPropertyDescriptors();
        return new HashMap<String, Object>(){{
            for (PropertyDescriptor property : propertyDescriptors) {
                Method getter = property.getReadMethod();
                String key = property.getName();
                if (getter != null && !"class".equals(key)) {
                    put(key, getter.invoke(entity));
                }
            }
        }};
    }
}
